package com.example.diet_sport.controller;

import com.alibaba.druid.pool.ha.selector.StickyDataSourceHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.diet_sport.entity.food;
import com.example.diet_sport.entity.user;
import com.example.diet_sport.mapper.foodMapper;
import com.example.diet_sport.mapper.userMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 伽蓝尘
 * @create 2023-06-03 15:50
 */
@RequestMapping("/food")
@RestController
@CrossOrigin
public class foodController {

    @Autowired
    private foodMapper foodMapper;


    /**
     * 添加食物
     * @param food
     */
    @PostMapping("/add")
    @ResponseBody
    public int add(food food) {
        return foodMapper.insert(food);
    }
    /**
     * 获得用户列表
     * @return
     */
    @GetMapping("/foodList")
    public List<food> getFoodList() {
        return foodMapper.selectList(null);
    }


    @PostMapping("/update")
    public void changeFoodById(food food) {

        foodMapper.updateById(food);
    }


    @ResponseBody
    @PostMapping("/delete")
    public int deleteByName(String name ) {
        int id = queryIdByName(name);
        return foodMapper.deleteById(id);
    }

    /**
     * 模糊查询
     * @param name
     * @return
     */
    @GetMapping("/search")
    public List<food>searchFood(String name){
        QueryWrapper<food> wrapper = new QueryWrapper<>();
        wrapper.like("name",name);
        List<food> food = foodMapper.selectList(wrapper);
        System.out.println(food);
        return food;
    }

    /**
     * 根据名字查询id
     * @param name
     * @return
     */
    @GetMapping("/getid")
    public int queryIdByName(String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("name",name);
        return foodMapper.selectByMap(map).get(0).getId();
    }
}
